//
//  ReadTableViewController.m
//  product_B
//
//  Created by lanou on 16/5/29.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "ReadTableViewController.h"
#import "ReadDetailModel.h"
#import "ReadComment0TableViewCell.h"
#import "ReadComment1TableViewCell.h"
#import "ReadMainTableViewCell.h"
#import "ReadDetailCommentModel.h"
#import "ReadMainModel.h"
#import "ReadserialModel.h"
#import "ReadQuestionModel.h"
#import "ReadDetailQuestionTableViewCell.h"
#import "ReadDetailMainTableViewCell.h"
#import "ReadDetailSerialModel.h"
#import "ReadDetailQuestionModel.h"
#import "MusicPlayerModel.h"
#import "MusicView.h"
#import "ReadDetailViewController.h"
#import "UserViewController.h"
#import "CommentViewController.h"

@interface ReadTableViewController ()<UITableViewDataSource,UITableViewDelegate,UIWebViewDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *modelUrlArray;
@property (nonatomic,strong)NSMutableArray *commentUrlArray;
@property (nonatomic,strong)NSMutableArray *recommendUrlArray;
@property (nonatomic,strong)ReadDetailModel *model;
@property (nonatomic,strong)UIWebView *webView;
@property (nonatomic,strong)UIView *smallview;
@property (nonatomic,strong)NSMutableArray *recommendArray;
@property (nonatomic,strong)NSMutableArray *commentArray;
@property (nonatomic,strong)ReadDetailSerialModel *serialModel;
@property (nonatomic,strong)ReadDetailQuestionModel *questionModel;
@property (nonatomic,strong)NSString *lastID;
@property (nonatomic,strong)MusicPlayerManager *manager;
@property (nonatomic,strong)NSTimer *timer;
@property (nonatomic,strong)UIBarButtonItem *rightBarbutton;
@property (nonatomic,strong)MusicView *musicView;
@property (nonatomic,strong)NSTimer *publicTime;
@property (nonatomic,assign)BOOL isShow;
@property (nonatomic,strong)UITapGestureRecognizer *tap;
@property (nonatomic,strong)NSString *string;
@property (nonatomic,strong)FMDBManager *dataManager;
@end

@implementation ReadTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBar.translucent = NO;
     _tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    self.dataManager = [[FMDBManager alloc]init];
    
    self.manager = [MusicPlayerManager shareInstance];
    NSInteger height = 0;
    if (_isAdd) {
        height = 49;
    }
    NSArray *array = @[@"短篇",@"连载",@"问答"];
    self.navigationItem.title = array[_indexY];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 64 -50+height) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"ReadComment0TableViewCell" bundle:nil] forCellReuseIdentifier:@"cell1"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ReadComment1TableViewCell" bundle:nil] forCellReuseIdentifier:@"cell2"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ReadMainTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell3"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ReadDetailMainTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell4"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ReadDetailQuestionTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell5"];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 2;
    [self.view addSubview:_tableView];
    
    self.modelUrlArray = [@[[NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/essay/%@",_modelID],[NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/serialcontent/%@",_modelID],[NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/question/%@",_modelID]]mutableCopy];
    
    self.commentUrlArray = [@[[NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/comment/praiseandtime/essay/%@/0",_modelID],[NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/comment/praiseandtime/serial/%@/0",_modelID],[NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/comment/praiseandtime/question/%@/0",_modelID]]mutableCopy];
    
    self.recommendUrlArray = [@[[NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/related/essay/%@",_modelID],[NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/related/serial/%@",_modelID],[NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/related/question/%@",_modelID]]mutableCopy];
    
    self.smallview = [[UIView alloc]initWithFrame:CGRectMake(0, kHeight-64-50, kWidth, 50)];
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 1)];
    topView.backgroundColor = [UIColor grayColor];
    self.loveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.loveButton.frame = CGRectMake(kWidth / 375 * 20, 15, kWidth / 375 *20, kWidth / 375 *20);
    
    [self.loveButton addTarget:self action:@selector(loveButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.loveButton setBackgroundImage:[UIImage imageNamed:@"爱心.png"] forState:UIControlStateNormal];
    [self.smallview addSubview:_loveButton];
    self.commentButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.commentButton.frame = CGRectMake(kWidth / 375 *70, 15, kWidth / 375 *20, kWidth / 375 *20);
    [self requestWork];
    [self.commentButton addTarget:self action:@selector(commentButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.commentButton setBackgroundImage:[UIImage imageNamed:@"评论.png"] forState:UIControlStateNormal];
    [self.smallview addSubview:_commentButton];
    
    self.topLoadButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.topLoadButton.frame = CGRectMake(kWidth / 375 *120, 15, kWidth / 375 *20, kWidth / 375 *20);
    
    [self.topLoadButton addTarget:self action:@selector(topLoadButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.topLoadButton setBackgroundImage:[UIImage imageNamed:@"分享.png"] forState:UIControlStateNormal];
    [self.smallview addSubview:_topLoadButton];
    
    self.commentLabel = [[UILabel alloc]initWithFrame:CGRectMake(kWidth / 375 *170, 10, kWidth / 375 * 90, 20)];
    self.commentLabel.textAlignment = NSTextAlignmentRight;
    self.commentLabel.textColor = [UIColor grayColor];
    [self.smallview addSubview:self.commentLabel];
    self.smallview.hidden = YES;
    self.loveLabel = [[UILabel alloc]initWithFrame:CGRectMake(kWidth / 375 *260, 10, 100, 20)];
    self.loveLabel.textColor = [UIColor grayColor];
    [self.smallview addSubview:_loveLabel];
    self.smallview.backgroundColor = [UIColor whiteColor];
    [self.smallview addSubview:topView];
    [self.view addSubview:self.smallview];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if(self.commentArray.count == 0){
            self.lastID = @"0";
        }else{
            
            ReadDetailCommentModel *model = self.commentArray.lastObject;
            if ([model.myID isEqualToString:@"000"]) {
                model = self.commentArray[self.commentArray.count - 2];
            }
            self.lastID = model.myID;
        }
        [self requestFootWork];
    }];
    
//    self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 64, kWidth, kHeight - 64)];
//    self.webView.backgroundColor = [UIColor whiteColor];
//    self.webView.delegate =self;
//    self.tableView.tableHeaderView = _webView;
    self.musicView = [[MusicView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 150)];
    
    self.musicView.backgroundColor = [UIColor whiteColor];
    
    self.musicView.layer.shadowOffset = CGSizeMake(1, 1);
    self.musicView.layer.shadowColor = [UIColor blackColor].CGColor;
    self.musicView.layer.shadowOpacity = 5;
    self.musicView.layer.shadowRadius = 1;
    self.musicView.layer.cornerRadius = 10;
    self.musicView.title.frame = CGRectMake(10, 70, 250, 90);
    self.musicView.title.numberOfLines = 0;
    self.musicView.title.textColor = [UIColor grayColor];
    [self.view addSubview:self.musicView];
    self.musicView.hidden = YES;
    
    self.publicTime = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(publicTimeAction) userInfo:nil repeats:YES];
    
    if (_indexY == 0) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    }
    
    self.rightBarbutton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"音乐 旋转.png.png"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarbuttonAction:)];
    
    
    self.navigationItem.rightBarButtonItem = _rightBarbutton;
    
    //    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc]initWithTitle:@"＜阅读" style:UIBarButtonItemStyleDone target:self action:@selector(leftButtonAction:)];
    //    self.navigationItem.leftBarButtonItem = leftButton;
    [self.dataManager openDB];
    [self.dataManager deleteReadCommentTableWithTableName:@"readComment" forURL:self.modelUrlArray[_indexY] myID:@"000"];
}
- (void)tapAction:(UITapGestureRecognizer *)tap{
    UITableViewCell *cell = (UITableViewCell *)tap.view.superview.superview;
    NSIndexPath *indexpath = [_tableView indexPathForCell:cell];
    UserViewController *userVC = [[UserViewController alloc]init];
    if (indexpath.section == 0) {
        if (_indexY == 0) {
            userVC.modelID = _model.author[0][@"user_id"];
        }else{
            userVC.modelID = _serialModel.author[@"user_id"];
        }
        
    }else{
        ReadDetailCommentModel *model = self.commentArray[indexpath.row];
        userVC.modelID = model.user[@"user_id"];
    }
    
    
    [self.navigationController pushViewController:userVC animated:YES];
}
- (void)publicTimeAction{
    if ([MusicPlayerManager shareInstance].player.currentItem.duration.timescale == 0 || [MusicPlayerManager shareInstance].player.currentTime.timescale == 0) {
        return;
    }
    long long int currentTime = [MusicPlayerManager shareInstance].player.currentTime.value / [MusicPlayerManager shareInstance].player.currentTime.timescale;
    long long int allTime = [MusicPlayerManager shareInstance].player.currentItem.duration.value / [MusicPlayerManager shareInstance].player.currentItem.duration.timescale;
    
    if (currentTime == allTime) {
        [[MusicPlayerManager shareInstance]replaceItemWithUrlString:[MusicPlayerManager shareInstance].playUrl];
    }
    
    
}
- (void)rightBarbuttonAction:(UIBarButtonItem *)button{
    [_musicView setMusicViewWithModel:[MusicPlayerManager shareInstance].musicModel];
    if (!_isShow) {
        self.musicView.hidden = NO;
        [self.view bringSubviewToFront:self.musicView];
        [self.musicView.button addTarget:self action:@selector(musicViewButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        if ([MusicPlayerManager shareInstance].isPlay) {
            [self.musicView.button setBackgroundImage:[UIImage imageNamed:@"暂停.png"] forState:UIControlStateNormal];
        }else{
            [self.musicView.button setBackgroundImage:[UIImage imageNamed:@"播放.png"] forState:UIControlStateNormal];
        }
    }else{
        self.musicView.hidden = YES;
    }
    _isShow = !_isShow;
}

- (void)musicViewButtonAction:(UIButton *)sender{
    if ([MusicPlayerManager shareInstance].isPlay) {
        [sender setBackgroundImage:[UIImage imageNamed:@"播放.png"] forState:UIControlStateNormal];
    }else{
        [sender setBackgroundImage:[UIImage imageNamed:@"暂停.png"] forState:UIControlStateNormal];
    }
    
    [_manager playerPlayAndPause];
    
}

- (void)timerAction{
    
    ReadDetailMainTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    if ([_manager.playUrl isEqualToString:self.model.audio]) {
        if (_manager.isPlay) {
            cell.playLabel.text = @"停止";
            [cell.playButton setBackgroundImage:[UIImage imageNamed:@"暂停.png"] forState:UIControlStateNormal];
        }else{
            cell.playLabel.text = @"收听";
            [cell.playButton setBackgroundImage:[UIImage imageNamed:@"播放.png"] forState:UIControlStateNormal];
        }
    }else{
        cell.playLabel.text = @"收听";
        [cell.playButton setBackgroundImage:[UIImage imageNamed:@"播放.png"] forState:UIControlStateNormal];
        
    }
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBarHidden = NO;
    if (!_manager.isPlay) {
        self.navigationItem.rightBarButtonItem = nil;
    }else{
        self.navigationItem.rightBarButtonItem = self.rightBarbutton;
    }
    [_dataManager openDB];
    [_dataManager createTableNameWithTableName:@"readComment"];
    
    if (_commentArray.count!=0) {
        [_commentArray removeAllObjects];
    }
    NSMutableArray *array = [_dataManager selectReadCommentTableWithTableName:@"readcomment" forURL:self.modelUrlArray[_indexY] type:@0];
    NSMutableArray *array1 = [_dataManager selectReadCommentTableWithTableName:@"readcomment" forURL:self.modelUrlArray[_indexY] type:@1];
    [self.commentArray addObjectsFromArray:array];
    [self.commentArray addObjectsFromArray:array1];
    [self.tableView reloadData];
    
}

- (void)requestFootWork{
    NSString *url = self.commentUrlArray[_indexY];
    [RequestManager initWithUrlString:[NSString stringWithFormat:@"%@%@",[url substringToIndex:url.length - 1],_lastID] requestType:@"GET" parDic:nil finishBlock:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *array = [ReadDetailCommentModel readDetailCommentModelWithConfigure:dic];
        for (ReadDetailCommentModel *model in array) {
            [self.commentArray addObject:model];
        }
        [self.tableView reloadData];
        [self performSelector:@selector(test) withObject:nil afterDelay:1];
        
    } errorBlock:^(NSError *error) {
        
    }];
    
}
- (void)test{
    [self.tableView.mj_footer endRefreshing];
}
- (void)requestWork{
    [RequestManager initWithUrlString:self.modelUrlArray[_indexY] requestType:@"GET" parDic:nil finishBlock:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if (_indexY == 0) {
            self.model = [[ReadDetailModel alloc]init];
            [self.model setValuesForKeysWithDictionary:dic[@"data"]];
        }else if (_indexY == 1)
        {
            self.serialModel = [[ReadDetailSerialModel alloc]init];
            [self.serialModel setValuesForKeysWithDictionary:dic[@"data"]];
        }else{
            self.questionModel = [[ReadDetailQuestionModel alloc]init];
            [self.questionModel setValuesForKeysWithDictionary:dic[@"data"]];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
//        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_model.web_url]];
//        [self.webView loadRequest:request];
//        self.tableView.tableHeaderView = _webView;
        
        self.smallview.hidden = NO;
        if (_indexY == 0) {
            self.commentLabel.text = [NSString stringWithFormat:@"%d",self.model.praisenum.intValue];
            self.loveLabel.text = [NSString stringWithFormat:@"赞.  %d评论",self.model.commentnum.intValue];
        }else if (_indexY == 1){
            self.commentLabel.text = [NSString stringWithFormat:@"%d",self.serialModel.praisenum.intValue];
            self.loveLabel.text = [NSString stringWithFormat:@"赞.  %d评论",self.serialModel.commentnum.intValue];
        }else{
            self.commentLabel.text = [NSString stringWithFormat:@"%d",self.questionModel.praisenum.intValue];
            self.loveLabel.text = [NSString stringWithFormat:@"赞.  %d评论",self.questionModel.commentnum.intValue];
        }
        
    } errorBlock:^(NSError *error) {
        
    }];
        [RequestManager initWithUrlString:self.recommendUrlArray[_indexY] requestType:@"GET" parDic:nil finishBlock:^(NSData *data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            if (_indexY == 0) {
                self.recommendArray = [ReadMainModel readDetailModelWithConfigure:dic];
            }else if (_indexY == 1){
                self.recommendArray = [ReadserialModel readDetailSerialModelWithConfigure:dic];
            }else{
                self.recommendArray = [ReadQuestionModel readDetailQuestionModelWithConfigure:dic];
            }
            [self.tableView reloadData];
        } errorBlock:^(NSError *error) {
            
        }];
        
        [RequestManager initWithUrlString:self.commentUrlArray[_indexY] requestType:@"GET" parDic:nil finishBlock:^(NSData *data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            self.commentArray = [ReadDetailCommentModel readDetailCommentModelWithConfigure:dic];
            
            for (ReadDetailCommentModel *model in _commentArray) {
                [_dataManager insertReadCommentTableWithTableName:@"readComment" url:self.modelUrlArray[_indexY] content:model.content myID:model.myID type:model.type input_date:model.input_date praisenum:model.praisenum quote:model.quote touser_name:model.touser[@"user_name"] user_id:model.user[@"user_id"] user_name:model.user[@"user_name"] web_url:model.user[@"web_url"]];
            }
            [self.commentArray removeAllObjects];
            [_dataManager openDB];
            [_dataManager createTableNameWithTableName:@"readComment"];
            
            if (_commentArray.count!=0) {
                [_commentArray removeAllObjects];
            }
            NSMutableArray *array = [_dataManager selectReadCommentTableWithTableName:@"readcomment" forURL:self.modelUrlArray[_indexY] type:@0];
            NSMutableArray *array1 = [_dataManager selectReadCommentTableWithTableName:@"readcomment" forURL:self.modelUrlArray[_indexY] type:@1];
            [self.commentArray addObjectsFromArray:array];
            [self.commentArray addObjectsFromArray:array1];
            [self.tableView reloadData];
        } errorBlock:^(NSError *error) {
            
        }];
        
    
    
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSInteger height =  [[_webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"] floatValue ];
    _webView.frame = CGRectMake(0, 64, kWidth, height);
    self.tableView.tableHeaderView = _webView;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    else if (section == 1) {
        return self.recommendArray.count;
    }else{
        return _commentArray.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (_indexY == 0) {
            ReadDetailMainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell4" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            if (self.model) {
                if ([self.model.audio isEqualToString:@""]) {
                    cell.playButton.hidden = YES;
                    cell.playLabel.hidden = YES;
                }else{
                    
                }
                
                [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:self.model.author[0][@"web_url"]]];
                cell.picImageView.userInteractionEnabled = YES;
                cell.picImageView2.userInteractionEnabled = YES;
                
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
                [cell.picImageView addGestureRecognizer:tap];
                UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
                [cell.picImageView2 addGestureRecognizer:tap2];
                cell.picImageView.layer.cornerRadius = 30;
                cell.picImageView.layer.masksToBounds = YES;
                [cell.picImageView2 sd_setImageWithURL:[NSURL URLWithString:self.model.author[0][@"web_url"]]];
                cell.picImageView2.layer.cornerRadius = 30;
                cell.picImageView2.layer.masksToBounds = YES;
                cell.nameLabel1.text = self.model.author[0][@"user_name"];
                cell.nameLabel2.text = self.model.author[0][@"user_name"];
                cell.dateLabel.text = [self.model.hp_makettime substringToIndex:10];
                cell.titleLabel.text = self.model.hp_title;
                self.model.hp_content = [self.model.hp_content stringByReplacingOccurrencesOfString:@"<br>" withString:@" "];
                
                if (self.model.hp_content.length >3800) {
                    cell.contentLabel.text = [self.model.hp_content substringToIndex:3800];
                    if (self.model.hp_content.length <= 7600) {
                        cell.content2Label.text = [self.model.hp_content substringFromIndex:3801];
                    }else{
                        cell.content2Label.text = [self.model.hp_content substringWithRange:NSMakeRange(3801, 3800)];
                        cell.content3Label.text = [self.model.hp_content substringFromIndex:7601];
                    }
                }else{
                    cell.contentLabel.text =  self.model.hp_content;
                }
                
                
                cell.editLabel.text = self.model.hp_author_introduce;
                cell.jobLabel.text = self.model.author[0][@"desc"];
                cell.wbLabel.text = self.model.author[0][@"wb_name"];
            }
            [cell.playButton addTarget:self action:@selector(cellButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            return cell;
            
        }else if (_indexY == 1){
            ReadDetailMainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell4" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if (self.serialModel) {
                [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:self.serialModel.author[@"web_url"]]];
                cell.picImageView.layer.cornerRadius = 30;
                cell.picImageView.layer.masksToBounds = YES;
                [cell.picImageView2 sd_setImageWithURL:[NSURL URLWithString:self.serialModel.author[@"web_url"]]];
                cell.picImageView.userInteractionEnabled = YES;
                cell.picImageView2.userInteractionEnabled = YES;
                
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
                [cell.picImageView addGestureRecognizer:tap];
                UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
                [cell.picImageView2 addGestureRecognizer:tap2];
                cell.picImageView2.layer.cornerRadius = 30;
                cell.picImageView2.layer.masksToBounds = YES;
                cell.nameLabel1.text = self.serialModel.author[@"user_name"];
                cell.nameLabel2.text = self.serialModel.author[@"user_name"];
                cell.dateLabel.text = [self.serialModel.maketime substringToIndex:10];
                cell.titleLabel.text = self.serialModel.title;
                self.serialModel.content = [self.serialModel.content stringByReplacingOccurrencesOfString:@"<br>" withString:@" "];
                cell.contentLabel.text = self.serialModel.content;
                cell.editLabel.text = self.serialModel.charge_edt;
                cell.jobLabel.text = self.serialModel.author[@"desc"];
                cell.playButton.hidden = YES;
                cell.playLabel.hidden = YES;
            }
            return cell;
        }else{
            ReadDetailQuestionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell5" forIndexPath:indexPath];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if (self.questionModel) {
                cell.questionLabel.text = self.questionModel.question_title;
                self.questionModel.question_content = [self.questionModel.question_content stringByReplacingOccurrencesOfString:@"<br>" withString:@" "];
                cell.questionContentLabel.text = self.questionModel.question_content;
                cell.answerLabel.text = self.questionModel.answer_title;
                self.questionModel.answer_content = [self.questionModel.answer_content stringByReplacingOccurrencesOfString:@"<br>" withString:@" "];
                cell.answerContentLabel.text = self.questionModel.answer_content;
                cell.editLabel.text = self.questionModel.charge_edt;
            }
            return cell;
        }
    }
    else if (indexPath.section == 1) {
        ReadMainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell3" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSArray *array = @[@"短篇",@"连载",@"问答"];
        if (_indexY == 0) {
            ReadMainModel *model = _recommendArray[indexPath.row];
            
            cell.titleLabel.text = model.hp_title;
            NSDictionary *dic = model.author[0];
            cell.authorLabel.text = dic[@"user_name"];
            cell.contentLabel.text= model.guide_word;
        }else if (_indexY == 1){
            ReadserialModel *model = _recommendArray[indexPath.row];
            cell.titleLabel.text  = model.title;
            cell.authorLabel.text = model.author[@"user_name"];
            cell.contentLabel.text = model.excerpt;
        }else{
            ReadQuestionModel *model = _recommendArray[indexPath.row];
            cell.titleLabel.text = model.question_title;
            cell.authorLabel.text = model.answer_title;
            cell.contentLabel.text = model.answer_content;
        }
        [cell.button setTitle:array[_indexY] forState:UIControlStateNormal];
        cell.button.layer.borderColor = [UIColor blueColor].CGColor;
        cell.button.layer.cornerRadius = 5;
        cell.button.layer.borderWidth = 1;
        cell.button.alpha = 0.5;
        cell.layer.cornerRadius = 5;
        
        return cell;
    }else{
        ReadDetailCommentModel *model = self.commentArray[indexPath.row];
        if (model.touser == nil) {
            ReadComment0TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1" forIndexPath:indexPath];
            
            
                [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:model.user[@"web_url"]]];
            cell.picImageView.layer.cornerRadius = 17.5;
            cell.picImageView.layer.masksToBounds = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
            cell.picImageView.userInteractionEnabled = YES;
            [cell.picImageView addGestureRecognizer:tap];
            cell.nameLabel.text = model.user[@"user_name"];
            cell.dateLabel.text = model.input_date;
            cell.numLabel.text = [NSString stringWithFormat:@"%d",model.praisenum.intValue];
            cell.commentLabel.text = model.content;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else{
            ReadComment1TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2" forIndexPath:indexPath];
            [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:model.user[@"web_url"]]];
            cell.picImageView.layer.cornerRadius = 17.5;
            cell.picImageView.layer.masksToBounds = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
            cell.picImageView.userInteractionEnabled = YES;
            [cell.picImageView addGestureRecognizer:tap];
            cell.nameLabel.text = model.user[@"user_name"];
            cell.dateLabel.text = model.input_date;
            cell.numLabel.text = [NSString stringWithFormat:@"%d",model.praisenum.intValue];
            cell.comment0Label.text = [NSString stringWithFormat:@"%@:%@",model.touser[@"user_name"],model.quote];
            cell.comment1Label.text = model.content;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    }
}
- (void)cellButtonAction:(UIButton *)sender{
    ReadDetailViewController *vc = (ReadDetailViewController *)self.parentViewController;
    MusicPlayerModel *model = [[MusicPlayerModel alloc]init];
    model.picture = self.model.author[0][@"web_url"];
    model.author = self.model.author[0][@"user_name"];
    model.title = self.model.hp_title;
    _manager.musicModel = model;
    ReadDetailMainTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    
    if ([_manager.playUrl isEqualToString:self.model.audio]) {
        if (!_manager.isPlay) {
            cell.playLabel.text = @"停止";
            [sender setBackgroundImage:[UIImage imageNamed:@"暂停.png"] forState:UIControlStateNormal];
            if (!_isRihgt) {
                vc.navigationItem.rightBarButtonItem = vc.rightBarbutton;
            }else{
                self.navigationItem.rightBarButtonItem = self.rightBarbutton;
            }
            
        }else{
            cell.playLabel.text = @"收听";
            [sender setBackgroundImage:[UIImage imageNamed:@"播放.png"] forState:UIControlStateNormal];
            if (!_isRihgt) {
                vc.navigationItem.rightBarButtonItem = nil;
            }else{
                self.navigationItem.rightBarButtonItem = nil;
            }
        }
        [_manager playerPlayAndPause];
        
    }else{
        cell.playLabel.text = @"停止";
        [sender setBackgroundImage:[UIImage imageNamed:@"暂停.png"] forState:UIControlStateNormal];
        [_manager replaceItemWithUrlString:self.model.audio];
        
        if (!_isRihgt) {
            vc.navigationItem.rightBarButtonItem = vc.rightBarbutton;
        }else{
            self.navigationItem.rightBarButtonItem = self.rightBarbutton;
        }
    }
    
    
    
  
    
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return nil;
    }
    else if (section == 1) {
        if (self.recommendArray.count == 0) {
            return nil;
        }
        return @"相关推荐";
    }else{
        return @"评论列表";
    }
}
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    return 20;
//}
- (void)loveButtonAction:(UIButton *)sender{
    _commentLabel.text = [NSString stringWithFormat:@"%ld",_commentLabel.text.integerValue + 1];
}
- (void)commentButtonAction:(UIButton *)sender{
    CommentViewController *comment = [[CommentViewController alloc]init];
    comment.url = self.modelUrlArray[_indexY];
    [self.navigationController pushViewController:comment animated:YES];
}
- (void)topLoadButtonAction:(UIButton *)sender{
    NSArray *imageArray = @[];
    NSString *web_url;
    NSString *title;
    NSString *text;
    if (_indexY == 0) {
        imageArray = @[_model.author[0][@"web_url"]];
        web_url= _model.web_url;
        title = _model.hp_title;
        text = _model.hp_content;
    }else if(_indexY == 1){
        imageArray = @[_serialModel.author[@"web_url"]];
        web_url= _serialModel.web_url;
        title = _serialModel.title;
        text = _serialModel.content;
    }else{
        imageArray = @[[UIImage imageNamed:@"用户小记.png"]];
        web_url= _questionModel.web_url;
        title = _questionModel.question_title;
        text = _questionModel.question_content;
    }
    
    // （注意：图片必须要在Xcode左边目录里面，名称必须要传正确，如果要分享网络图片，可以这样传iamge参数 images:@[@"http://mob.com/Assets/images/logo.png?v=20150320"]）
    if (imageArray) {
        
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:[text substringToIndex:100]
                                         images:imageArray
                                            url:[NSURL URLWithString:web_url]
                                          title:title
                                           type:SSDKContentTypeAuto];
        //2、分享（可以弹出我们的分享菜单和编辑界面）//要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
        
        [ShareSDK showShareActionSheet:nil
         
                                 items:nil
                           shareParams:shareParams
                   onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                       
                       switch (state) {
                           case SSDKResponseStateSuccess:
                           {
                               [self alert:@"分享成功"];
                               break;
                           }
                           case SSDKResponseStateFail:
                           {
                               [self alert:@"分享失败"];
                               break;
                           }
                           default:
                               break;
                       }
                   }
         ];}
}
- (void)alert:(NSString *)string{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:string preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:nil];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancel];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        ReadTableViewController *tableVC = [[ReadTableViewController alloc]init];
        
        if (self.indexY == 0) {
            ReadMainModel *model = self.recommendArray[indexPath.row];
            tableVC.modelID = model.content_id;
        }else if (_indexY == 1){
            ReadserialModel *model = self.recommendArray[indexPath.row];
            tableVC.modelID = model.myID;
        }else{
            ReadQuestionModel *model = self.recommendArray[indexPath.row];
            tableVC.modelID = model.question_id;
        }
        tableVC.indexY = _indexY;
        tableVC.isAdd = YES;
        [self.navigationController pushViewController:tableVC animated:YES];
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
